package com.kasax.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.util.Log
import java.util.Stack

class AppActivityManager private constructor() {
    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity) {
        if (mStack == null) {
            mStack = Stack()
        }
        mStack!!.add(activity)
        Log.i("------------------>", mStack!!.size.toString() + "")
    }

    /**
     * 移除Activity到堆外
     */
    fun removeActivity(activity: Activity) {
        mStack!!.remove(activity)
    }

    val topActivity: Activity
        /**
         * 获取栈顶Activity
         */
        get() = mStack!!.lastElement()

    /**
     * 结束栈顶Activity
     */
    fun killTopActivity() {
        val activity = mStack!!.lastElement()
        killActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    private fun killActivity(activity: Activity?) {
        if (activity != null) {
            mStack!!.remove(activity)
        }
        activity!!.finish()
    }

    /**
     * 结束指定类名的Activity
     */
    fun killActivity(cls: Class<*>) {
        for (activity in mStack!!) {
            if (activity.javaClass == cls) {
                killActivity(activity)
            }
        }
    }

    /**
     * 退出应用程序
     */
    @Suppress("deprecation")
    fun exitApp(context: Context) {
        try {
            killAllActivity()
            val activityMgr = context
                .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            activityMgr.restartPackage(context.packageName)
            System.exit(0)
        } catch (e: Exception) {
            Log.e("AppActivityManager", "" + e)
        }
    }

    /**
     * 结束所有Activity
     */
    private fun killAllActivity() {
        val size = mStack!!.size
        for (i in 0..<size) {
            if (null != mStack!![i]) {
                mStack!![i].finish()
            }
        }
        mStack!!.clear()
    }

    companion object {
        private var mStack: Stack<Activity>? = null
        private var mAppCompatActivity: AppActivityManager? = null

        @JvmStatic
        val instance: AppActivityManager
            /**
             * 单一实例
             */
            get() {
                if (mAppCompatActivity == null) {
                    mAppCompatActivity = AppActivityManager()
                }
                return mAppCompatActivity!!
            }


    }
}
